<template>
  <el-dialog v-model="userStore.dialogFormVisible" title="用户登录" width="800">
    <div class="login-form">
      <div class="left">
        <div class="left-form">
          <el-form :model="form" v-show="scene === 0" :rules="rules">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" :prefix-icon="User" placeholder="请输入手机号" clearable></el-input>
            </el-form-item>
            <el-form-item label="验证码" prop="code">
              <el-input v-model="form.code" :prefix-icon="Lock" placeholder="请输入验证码" clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="info" plain @click="handleGetCode" :disabled="!isPhone || isCounting">
                {{ isCounting ? `${countdownTime}秒后重新获取` : '获取验证码' }}
              </el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" style="width: 100%" @click="handelLogin">
                用户登录
              </el-button>
            </el-form-item>
            <div class="left-desc" @click="changeScene">
              <p>微信扫码登录</p>
              <img src="@/assets/WeChat-1.png" alt="微信登录"/>
            </div>
          </el-form>
          <div class="wechat-login" v-show="scene === 1">

            <!-- 在这个容器当中显示微信扫码登录页面 -->
            <div id="login_container"></div>

            <!--            <img src="@/assets/images/code_login_wechat.png" alt="微信登录"-->
            <!--                 style="width: 220px; height: 220px;margin-bottom: 20px;"/>-->
            <div class="left-desc" @click="changeScenePhone">
              <p>手机验证码登录</p>
              <img src="@/assets/Phone-1.png" alt="手机验证码登录"/>
            </div>
          </div>
        </div>
      </div>

      <div class="right">
        <div class="images">
          <div class="img-1">
            <img src="@/assets/images/code_login_wechat.png" alt="微信登录"/>
            <div class="desc">
              <img src="@/assets/WeChat.png" alt="微信号"/>
              <p>微信扫一扫关注</p>
              <p>"快速预约挂号"</p>
            </div>
          </div>
          <div class="img-2">
            <img src="@/assets/images/code_app.png" alt="APP登录"/>
            <div class="desc">
              <img src="@/assets/Phone.png" alt="手机号"/>
              <p>扫一扫下载</p>
              <p>"预约挂号"APP</p>
            </div>
          </div>
        </div>
        <div class="text">
          <p>小医通官方指定平台</p>
          <p>快速挂号&nbsp;&nbsp;安全放心</p>
        </div>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="userStore.dialogFormVisible = false">关闭窗口</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import {reactive, ref, computed, onMounted} from 'vue'
import {User, Lock} from '@element-plus/icons-vue'
import {useUserStore} from '@/store/modules/user.js'
import {ElMessage} from "element-plus";
import {useRouter} from 'vue-router'
// 引入微信扫码登录
import {reqWxLogin} from "@/api/user/index.js";

const router = useRouter()

const userStore = useUserStore()
// 挂载之后获取用户信息
onMounted(() => {
  const userInfo = userStore.getUserInfo()
  if (userInfo.token) {
    userStore.setUserInfo(userInfo)
  }
})

// 收集表单数据
const form = reactive({
  phone: "",
  code: "",
})
// 表单自定义验证规则
const validatorPhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入手机号"))
  } else if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error("手机号格式不正确"))
  } else {
    callback()
  }
}
const validatorCode = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入验证码"))
  } else if (value.length !== 6) {
    callback(new Error("验证码格式不正确"))
  } else {
    callback()
  }
}
const rules = {
  phone: [{required: true, trigger: "change", validator: validatorPhone}],
  code: [{required: true, message: "请输入正确的验证码", min: 6, trigger: "change", validator: validatorCode}],
}
const isPhone = computed(() => {
  return /^1[3-9]\d{9}$/.test(form.phone)
})

// 左侧登录表单与微信扫码登录
const scene = ref(0)
const changeScene = async () => {
  scene.value = 1
//   获取微信扫码登录参数生成二维码
  const redirect_URL = encodeURIComponent(window.location.origin + "/wxLogin")

  let result = await reqWxLogin(redirect_URL)
  new WxLogin({
    self_redirect: true, //true:手机点击确认登录后可以在 iframe 内跳转到 redirect_uri
    id: "login_container", //显示二维码容器设置
    appid: result.data.appid, //应用位置标识appid
    scope: "snsapi_login", //当前微信扫码登录页面已经授权了
    redirect_uri: result.data.redirectUri, //填写授权回调域路径,就是用户授权成功以后，微信服务器向公司后台推送code地址
    state: result.data.state, //state就是学校服务器重定向的地址携带用户信息
    style: "black",
    href: "",
  });

}
const changeScenePhone = () => {
  scene.value = 0
}

// 倒计时功能
const countdownTime = ref(10) // 设置倒计时时间为60秒
const isCounting = ref(false)
const handleGetCode = async () => {
  if (isCounting.value) return; // 如果正在倒计时，则不进行操作
  if (!isPhone.value) {
    ElMessage.error("请输入正确的手机号")
    return;
  }
  try {
    await userStore.getCode(form.phone)
    form.code = userStore.code
    ElMessage.success("验证码发送成功")
    // 启动倒计时
    isCounting.value = true
    let countdownInterval = setInterval(() => {
      if (countdownTime.value > 0) {
        countdownTime.value--;
      } else {
        clearInterval(countdownInterval);
        countdownTime.value = 10; // 重置倒计时时间
        isCounting.value = false;
      }
    }, 1000);

  } catch (error) {
    ElMessage.error("验证码发送失败")
  }
}

// 登录
const handelLogin = async () => {
  if (!isPhone.value) {
    ElMessage.error("请输入正确的手机号")
  } else if (!form.code || form.code.length !== 6) {
    ElMessage.error("请输入正确的验证码")
  }
  try {
    await userStore.getLogin({
      phone: form.phone,
      code: form.code,
    })
    userStore.dialogFormVisible = false
    ElMessage.success("登录成功")
    await router.push('/home')
  } catch (error) {
    ElMessage.error("登录失败")
  }
}

</script>


<style scoped lang="scss">
.wechat-login {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.login-form {
  display: flex;
  justify-content: space-between;
  height: 100%;
  padding: 15px;
  background-color: #f7fbff;


  .left {
    width: 50%;
    margin-right: 10px;
    display: flex;
    flex-direction: column;

    .left-form {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      border-radius: 10px;
      padding: 15px 10px;
      margin-right: 10px;
      background-color: #ffffff;
      box-shadow: 0 0 20px 0 rgba(73, 144, 241, .2);

      .left-desc {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;

        &:hover {
          font-weight: bold;
          cursor: pointer;
          transform: scale(1.1);
        }

        p {
          font-size: 16px;
          color: #838383;
          margin-bottom: 5px;
        }

        img {
          width: 30px;
          height: 30px;
        }
      }
    }
  }

  .right {
    width: 50%;
    margin-left: 10px;
    display: flex;
    flex-direction: column;
    align-items: center;

    .images {
      display: flex;
      justify-content: center;
      align-items: center;

      .img-1, .img-2 {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin: 0 10px;

        img {
          width: 150px;
          height: 150px;
        }

        .desc {
          display: flex;
          flex-direction: column;
          align-items: center;
          margin: 5px;

          p {
            font-size: 14px;
            color: #838383;
            margin-bottom: 5px;
          }

          img {
            width: 30px;
            height: 30px;
          }
        }
      }
    }

    .text {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-top: 20px;

      p {
        font-size: 20px;
        color: #838383;
        margin: 15px;
        font-style: italic;
        font-weight: bold;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px;
  border-top: 1px solid #f8f8f8;
  background-color: #f7fbff;
}


</style>